<?php

namespace app\api\controller;

use think\Db;

class SheinSDK
{
    private $openkeyid ;
    private $secretkey ;
    private $domain ;//希音测试域名

    public function __construct()
    {
        $this->openkeyid = '0F8914983B7F43859745C817314F4645';
        $this->secretkey = 'DC0F496E58404B8884D1F32B1D6915D8';
        $this->domain = 'https://open.sheincorp.com/';

    }

    /**
     * @use curl 请求
     * @param $header
     * @param $url
     * @param $params
     * @return bool|string|void
     * @time 2024/8/23 9:19
     * @by Hugh
     */
    public function curl($header,$url,$params = [],$request_type)
    {


        if ($request_type == 'POST'){
            $json_params = json_encode($params,true);
        }else{
            if ($params){
                $params = http_build_query($params);
                $url .= '?'.$params;
            }
            $json_params = '';
        }
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $this->domain.$url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER =>false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $request_type,
            CURLOPT_POSTFIELDS => $json_params,
            CURLOPT_HTTPHEADER => $header,
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            return "cURL Error #:" . $err;
        } else {
            return $response;
        }
    }


    /**
     * @use 拼接数据,准备请求
     * @param $url
     * @param $params
     * @return mixed
     * @time 2024/8/23 9:18
     * @by Hugh
     */
    public function exce($url,$params,$request_type = 'POST')
    {
        $time = round(microtime(true) * 1000);
        $sign = $this->generateSign($url,$time);
        $header = [
            'Content-Type: application/json',
            'x-lt-openKeyId: '.$this->openkeyid,
            'x-lt-timestamp: '.$time,
            'x-lt-signature:'.$sign,
        ];
        $res = $this->curl($header,$url,$params,$request_type);
        return json_decode($res,true);

    }

    /**
     * @use 获取签名
     * @param $url
     * @param $time
     * @return string
     * @time 2024/8/23 9:18
     * @by Hugh
     */
    protected function generateSign($url,$time)
    {
        // value = x-lt-openKeyId + “&”+ x-lt-timestamp+“&”+requestPath
        $value = $this->openkeyid."&".$time."&".$url;
        //随机生成 5 位的随机码（下称：randomKey ）与 secretKey 拼起来，得到 key = secretKey + randomKey（假设为：1aa34），如：test1231aa34
        $randomKey = 'aa112';//5位随机码
        $key  = $this->secretkey.$randomKey;
        //前两步生成的 value 和 key 进行 hmacSha256 求值，最后对该值进行Base64加密，得到加密串：
        $str = base64_encode(hash_hmac('sha256', $value, $key, false));
        //将 randomKey 拼于加密串之前，得到最终签名：
        return $randomKey . $str;
    }

    /** 先吧多spu 单spu是多个的给拆单 拆成一客一单一件
     * @param $page
     * @return void
     */
    public function getSplitOrder($page = 0){
        $yesterday = date('Y-m-d',strtotime('-1 day'));
        $date = date('Y-m-d');
        if (date('H') < 14 ){
            $params = [
                'type' => 2,
                'combineTimeStart' => $yesterday.' 14:00:01',
                'combineTimeEnd' => $date.' 07:00:00',
                'pageNumber' => 1,
                'pageSize' => 200,
            ];
        }else{
            $params = [
                'type' => 2,
                'combineTimeStart' => $date.' 06:00:01',
                'combineTimeEnd' => $date.' 14:30:00',
                'pageNumber' => 1,
                'pageSize' => 200,
            ];
        }
        $date = '2025-07-24';
        $params = [
            'type' => 2,
            'combineTimeStart' => $date.' 14:00:01',
            'combineTimeEnd' => $date.' 23:00:00',
            'pageNumber' => 1,
            'pageSize' => 200,
        ];

        $url = '/open-api/order/purchase-order-infos';
        $res = $this->exce($url,$params,'GET');
        $total = $res['info']['count'];
        $page++;
        foreach($res['info']['list'] as $k => $v){
            $count = count($v['orderExtends']);
            $skc = '';
            // spu 是多个
            if ($count > 1 ){
                foreach($v['orderExtends'] as $k1 =>$v1){
                    $moreOrders = [];
                    $skc = $v1['skc'];
                    $quantity = $v1['orderQuantity'];
                    // 数量是多个
                    for($i = 1 ; $i < $quantity;$i++){
                        $moreOrders[] =
                            [
                                'orderDetails' => [["skuCode" => $v1['skuCode'], "quantity" => 1]],
                            ];
                    }
                    // 如果是多个spu 则最后一个spu保留 但是保证是最后一个spu只有一件货
                    if($k1 +1 == $count && empty($moreOrders)) {
                        break;
                    }

                    if ($moreOrders){
                        $params_split = [
                            'operator' => 'Mr朱',
                            'sellerOrderNo' => $v['orderNo'],
                            'skc' => $skc,
                            'splitOrders' => $moreOrders
                        ];

                        $method = '/open-api/pfmp/order/batch-split-order';
                        $res1 = $this->exce($method,$params_split,'POST');

                    }
                }
            }else{
                foreach($v['orderExtends'] as $k1 =>$v1){
                    $moreOrders = [];
                    $skc = $v1['skc'];
                    $quantity = $v1['orderQuantity'];
                    if ($quantity == 1 ){
                        break;
                    }
                    // 数量是多个
                    for($i = 1 ; $i < $quantity;$i++){
                        $moreOrders[] =
                            [
                                'orderDetails' => [["skuCode" => $v1['skuCode'], "quantity" => 1]],
                            ];
                    }
                    if ($moreOrders){
                        $params_split = [
                            'operator' => 'Mr朱',
                            'sellerOrderNo' => $v['orderNo'],
                            'skc' => $skc,
                            'splitOrders' => $moreOrders
                        ];

                        $method = '/open-api/pfmp/order/batch-split-order';
                        $res1 = $this->exce($method,$params_split,'POST');

                    }
                }

            }
        }

        if ($page * 200 < $total){
            $this->getOrder($orders,$page);
        }
        echo('拆单结束');
    }

    /**  获取订单
     * @param $order
     * @param $page
     * @return void
     */
    public function getOrders(&$orders,$page = 0)
    {
        $yesterday = date('Y-m-d',strtotime('-1 day'));
        $date = date('Y-m-d');
        if (date('H') < 14 ){
            $params = [
                'type' => 2,
                'combineTimeStart' => $yesterday.' 14:00:01',
                'combineTimeEnd' => $date.' 07:00:00',
                'pageNumber' => 1,
                'pageSize' => 200,
            ];
        }else{
            $params = [
                'type' => 2,
                'combineTimeStart' => $date.' 06:00:01',
                'combineTimeEnd' => $date.' 14:30:00',
                'pageNumber' => 1,
                'pageSize' => 200,
            ];
        }
        $date = '2025-07-24';
        $params = [
            'type' => 2,
            'combineTimeStart' => $date.' 14:00:01',
            'combineTimeEnd' => $date.' 23:00:00',
            'pageNumber' => 1,
            'pageSize' => 200,
        ];

        $url = '/open-api/order/purchase-order-infos';
        $res = $this->exce($url,$params,'GET');
        $total = $res['info']['count'];
        $page++;
        $list = Db::name('trade_shein')
            ->where('allocateTime','>',$date)
            ->column('id','orderNo');
        $insertAll = [];
        foreach($res['info']['list'] as $k => $v){
            $v = $this->change($v);
            if(isset($list[$v['orderNo']])){
                Db::name('trade_shein')
                    ->where('id',$list[$v['orderNo']])
                    ->update($v);
            }else{
                $insertAll[] = $v;
            }
        }
        if (!empty($insertAll)){
            Db::name('trade_shein')
                ->insertAll($insertAll);
        }

        if ($page * 200 < $total){
            $this->getOrders($orders,$page);
        }
        echo('拉单结束');
    }

    protected function change($info)
    {
        $return_info = array();
        $return_info['shop_id'] = 1;
        $return_info['shop'] = '希音店1';
        $return_info['outer_tid'] = $info['orderNo']; //外部交易编号

        $return_info['orderNo'] = $info['orderNo'];                //外部交易编号
        $return_info['typeName'] = $info['typeName'] ? $info['typeName'] : '';              //类型名称
        $return_info['supplierName'] = $info['supplierName'];      //商家名称

        $return_info['requestDeliveryTime'] = $info['requestDeliveryTime'] ?  $info['requestDeliveryTime'] : ''; //要求发货时间
        $return_info['addTime'] = $info['addTime'] ? $info['addTime'] : '';                        //添加时间
        $return_info['allocateTime'] = $info['allocateTime'] ? $info['allocateTime'] : '';              //分单时间

        $return_info['receiptTime'] = $info['receiptTime'] ? $info['receiptTime'] : '';    //收货时间
        $return_info['checkTime'] = $info['checkTime'] ? $info['checkTime'] : '';        //查验时间
        $return_info['storageTime'] = $info['storageTime'] ? $info['storageTime'] : '';    //入仓时间
        $return_info['returnTime'] = $info['returnTime'] ? $info['returnTime'] : '';   //退货时间
        $return_info['firstMarkName'] = $info['firstMarkName'] ? $info['firstMarkName'] : ''; //首单标识

        $return_info['warehouseName'] = $info['warehouseName'] ? $info['warehouseName'] : '';    //收货仓库id对应的仓库名称
        $return_info['urgentTypeName'] = $info['urgentTypeName'] ? $info['urgentTypeName'] : '';  //紧急类型 (普通 紧急 特急)

        $return_info['storageId'] = $info['storageId'];                                  //收货仓库id
        $return_info['isDeliveryName'] = $info['isDeliveryName'] ? $info['isDeliveryName'] : '';      //是否送货

        $return_info['currencyId'] = $info['currencyId'];
        $return_info['firstMark'] = $info['firstMark'];
        $return_info['orderMarkId'] = $info['orderMarkId'];
        $return_info['prepareTypeId'] = $info['prepareTypeId'];
        $return_info['category'] = $info['category'];

        $return_info['type'] = $info['type'];
        $return_info['status'] = $info['status'];
        $return_info['statusName'] = $info['statusName']; //状态名称
        $return_info['updateTime'] = $info['updateTime'] ? $info['updateTime'] : ''; //更新时间
        $return_info['isJitMotherName'] = $info['isJitMotherName'] ? $info['isJitMotherName'] : '';

        $return_info['isPriorProductionName'] = $info['isPriorProductionName'] ? $info['isPriorProductionName'] : '';
        $return_info['deliveryTime'] = $info['deliveryTime'] ? $info['deliveryTime'] : ''; //发货时间
        $return_info['customInfoId'] = $info['customInfoId'] ? $info['customInfoId'] : '';
        $return_info['customInfo'] = $info['customInfo'] ? $info['customInfo'] : '';
        $return_info['orderExtends'] = json_encode($info['orderExtends'], JSON_UNESCAPED_UNICODE);
        return $return_info;
    }
}